package uk.dier.account.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import uk.dier.account.dao.ISMarketDao;
import uk.dier.account.dto.MarketDto;
import uk.dier.account.entity.Market;
import uk.dier.account.exception.ExceptionDao;
import uk.dier.account.utils.DozerMapper;
import uk.dier.account.utils.HibernateSession;

@Repository
@Transactional
public class MarketDaoImpl extends HibernateSession implements ISMarketDao {

	public void saveMarket(Market newMarket) throws ExceptionDao{
		getSession().saveOrUpdate(newMarket);
	}

	public void deleteMarket(Market removeMarket) throws ExceptionDao{
		getSession().delete(removeMarket);
	}

	public void updateMarket(Market updateMarket) throws ExceptionDao{
		this.saveMarket(updateMarket);
	}

	@SuppressWarnings("unchecked")
	public List<MarketDto> findMarketByName(Market market) throws ExceptionDao {
		
		List<MarketDto> listOfMarquetDto = new ArrayList<MarketDto>();
		
		//Check name is not empty
		if (StringUtils.hasText(market.getMarketName())) {
			
			StringBuilder hql = new StringBuilder();
			//Build HQL
			hql.append("from Market m "); 
			hql.append("where m.marketName like '%" + market.getMarketName() + "%'");
			
			Query query = getSession().createQuery(hql.toString());
			
			//Check list is not empty
			if (!query.list().isEmpty()) {
				//Return list of Market
				List<Market> resultMarkets = query.list();
				for (Market result : resultMarkets) {
					//Map from Market to MarketDto
					listOfMarquetDto.add(DozerMapper.mapClass(result, MarketDto.class));
				}
			}
		}
		return listOfMarquetDto;
	}
}
